﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

namespace BlackHawkCoupons
{
    /// <summary>
    /// Summary description for Coupons
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    [ScriptService]
    public class CouponsAPI : WebService
    {

        [WebMethod()]
        public string GetCoupon(int CouponID)
        {
            dbCoupons db = new dbCoupons();

            var Coupons = (from c in db.t_Coupons
                                      where c.CouponID == CouponID
                                      select new
                                      {
                                          c.CouponID,
                                          c.CasinoID,
                                          c.StartDate,
                                          c.EndDate,
                                          c.Amount,
                                          c.Gotten
                                      }).ToList();


            Models.Coupon Coupon = new Models.Coupon();
            var cpn = Coupons.FirstOrDefault();
            Coupon.CouponID = cpn.CouponID;
            Coupon.CasinoID = cpn.CasinoID;
            Coupon.Amount = cpn.Amount;
            Coupon.StartDate = cpn.StartDate.ToShortDateString();
            Coupon.EndDate = cpn.EndDate.ToShortDateString();
            Coupon.Gotten = cpn.Gotten;
            return new JavaScriptSerializer().Serialize(Coupon);
        }

		//----------------------------------------------------------------------------------------------------
        [WebMethod]
        public string GetCoupons(
            string CasinoID
            , string StartDate
            , string EndDate
            , string AmountMin
            , string AmountMax
            , string Gotten
            , string NotGotten
			,string OrderBy)
        {
            dbCoupons db = new dbCoupons();
            int iCasinoID = (int.TryParse(CasinoID, out iCasinoID))
                ? Convert.ToInt32(CasinoID)
                : -1;
            DateTime RangeStartDate = (DateTime.TryParse(StartDate, out RangeStartDate))
                ? Convert.ToDateTime(StartDate)
                : db.t_Coupons.Min(c => c.StartDate);
            DateTime RangeEndDate = (DateTime.TryParse(EndDate, out RangeEndDate))
                ? Convert.ToDateTime(EndDate)
                : db.t_Coupons.Max(c => c.EndDate);
            decimal dAmountMin = (decimal.TryParse(AmountMin, out dAmountMin))
                ? Convert.ToDecimal(AmountMin)
                : 0;
            decimal dAmountMax = (decimal.TryParse(AmountMax, out dAmountMax))
                ? Convert.ToDecimal(AmountMax)
                : 100000;
            bool bGotten = (bool.TryParse(Gotten, out bGotten))
                ? Convert.ToBoolean(Gotten)
                : false;
            bool bNotGotten = (bool.TryParse(NotGotten, out bNotGotten))
                ? Convert.ToBoolean(NotGotten)
                : false;

			string[] arrOrderBy = OrderBy.Split(' ');
			string sOrderBy = (string.IsNullOrEmpty(arrOrderBy[0]) ? "StartDate" : arrOrderBy[0]);

			string sOrderByDir = (arrOrderBy.Length > 1 ? arrOrderBy[1] : "");


            string serializedCoupons = "";
            List<Models.Coupon> Coupons=new List<Models.Coupon>();
            if (bGotten || bNotGotten)
            {
                try
                {
					Coupons = (from c in db.t_Coupons
							   where
							   (
								   (
									   c.StartDate >= RangeStartDate
									   &&
									   c.StartDate <= RangeEndDate
								   )
								   ||
								   (
									   c.EndDate >= RangeStartDate
									   &&
									   c.EndDate <= RangeEndDate
								   )
								   ||
								   (
									   c.StartDate <= RangeStartDate
									   &&
									   c.EndDate >= RangeEndDate
								   )
							   )
							   &&
							   c.CasinoID == (iCasinoID > 0 ? iCasinoID : c.CasinoID)
							   &&
							   (
								   (
									   c.Amount >= dAmountMin
									   &&
									   c.Amount <= dAmountMax
								   )
								   &&
									   c.Gotten == (bGotten && bNotGotten
													   ? c.Gotten
													   : (bGotten ? true : false)
												   )
							   )

							   select new Models.Coupon()
							   {
								   CouponID = c.CouponID
								   ,
								   CasinoID = c.CasinoID
								   ,
								   CasinoName = c.t_Casino.Casino
								   ,
								   StartDate = c.StartDate.ToShortDateString()
								   ,
								   dtStartDate=c.StartDate
								   ,
								   dtEndDate=c.EndDate
								   ,
								   EndDate = c.EndDate.ToShortDateString()
								   ,
								   Amount = c.Amount
								   ,
								   Gotten = c.Gotten
							   }
					).ToList();

					switch (sOrderBy)
					{
						case "StartDate":
							if (sOrderByDir == "desc")
								Coupons = Coupons.OrderByDescending(c => c.dtStartDate).ThenBy(c => c.CasinoName).ToList();
							else
								Coupons = Coupons.OrderBy(c => c.dtStartDate).ThenBy(c => c.CasinoName).ToList();
							break;
						
						case "CasinoName":
							if (sOrderByDir == "desc")
								Coupons = Coupons.OrderByDescending(c => c.CasinoName).ThenBy(c => c.dtStartDate).ToList();
							else
								Coupons = Coupons.OrderBy(c => c.CasinoName).ThenBy(c => c.StartDate).ToList();
							break;
					}

					//if (sOrderByDir == "desc") { Coupons.Reverse(); }

					//Coupons.Sort((a, b) =>
					//{	
					//    System.Reflection.PropertyInfo aProp = a.GetType().GetProperty(sOrderBy);
					//    System.Reflection.PropertyInfo bProp = b.GetType().GetProperty(sOrderBy);
					//    object aVal = aProp.GetValue(a, null);
					//    object bVal = bProp.GetValue(b, null);

					//    int result;

					//    if (sOrderBy.ToLower().Contains("date"))
					//    {
					//        DateTime aDate = DateTime.Parse(aVal.ToString());
					//        DateTime bDate = DateTime.Parse(bVal.ToString());

					//        result =
					//            (aDate == bDate)
					//                ? 0
					//                : (aDate < bDate)
					//                    ? -1
					//                    : (aDate > bDate)
					//                        ? 1
					//                        : 0;
					//    }
					//    else
					//    {
					//        result = (aVal as IComparable).CompareTo(bVal as IComparable);
					//    }

					//    return result;

					//});

					

                    if (Coupons.Count() == 0)
                    {
                        serializedCoupons = "{failed:'No coupons found for selected criteria.'}";
                    }
                    else
                    {
                        serializedCoupons = new JavaScriptSerializer().Serialize(Coupons);
                    }

                }
                catch (Exception e)
                {
					serializedCoupons = "{failed:'" + e.Message.Replace("'", "") + "'}";
                }
            }
  
            return serializedCoupons;
        }

		//----------------------------------------------------------------------------------------------------
        [WebMethod]
        public string GetCasinos()
        {
            dbCoupons db = new dbCoupons();

			List<Models.Casino> Casinos = (from c in db.t_Casinos
										   select new Models.Casino
										   {
											   CasinoID = c.CasinoID
											   ,
											   CasinoName = c.Casino
										   }
										   ).OrderBy(c => c.CasinoName).ToList();


            return new JavaScriptSerializer().Serialize(Casinos);
        }

		//----------------------------------------------------------------------------------------------------
        [WebMethod]
        public string SaveCoupon(
            int CasinoID
            , string StartDate
            , string EndDate
            , decimal Amount
            , bool Gotten
            )
        {
            dbCoupons db = new dbCoupons();
            t_Coupon Coupon = new t_Coupon();

            Coupon.Amount = Amount;
            Coupon.CasinoID = CasinoID;
            Coupon.StartDate = DateTime.Parse(StartDate);
            Coupon.EndDate = DateTime.Parse(EndDate);
            Coupon.Gotten = Gotten;

            db.t_Coupons.InsertOnSubmit(Coupon);

            try
            {
                db.SubmitChanges();
                return "{msg:'success'}";
            }
            catch (Exception e)
            {
                return "{msg:'" + e.Message.ToString() + "'}";
            }
        }

		//----------------------------------------------------------------------------------------------------
        [WebMethod]
        public string UpdateGotten(string CouponID, string Gotten)
        {
            int iCouponID = int.Parse(CouponID);
            bool bGotten = bool.Parse(Gotten);

            dbCoupons db = new dbCoupons();
            t_Coupon Coupon = db.t_Coupons.SingleOrDefault(c => c.CouponID == iCouponID);

            string Results = "";

            Coupon.Gotten = bGotten;
            try
            {
                db.SubmitChanges();
                Results = "{status:'success'}";
            }
            catch (Exception c)
            {
                Results = "{status:'Update Failed'}";
            }

            return Results;
        }

		//----------------------------------------------------------------------------------------------------
		[WebMethod]
		public string UpdateCoupon(string sCouponID, string sStartDate, string sEndDate, string sAmount)
		{
			string status = "", message = "";
			int CouponID = int.Parse(sCouponID);
			DateTime StartDate = DateTime.Parse(sStartDate);
			DateTime EndDate = DateTime.Parse(sEndDate);
			decimal Amount = decimal.Parse(sAmount);

			dbCoupons db = new dbCoupons();
			t_Coupon Coupon = db.t_Coupons.SingleOrDefault(c => c.CouponID == CouponID);

			if (Coupon != null)
			{
				Coupon.StartDate = StartDate;
				Coupon.EndDate = EndDate;
				Coupon.Amount = Amount;

				try
				{
					db.SubmitChanges();
					status = "success";
				}
				catch(Exception e)
				{
					status = "failed";
					message = e.Message;
				}
			}
			else
			{
				status = "failed";
				message = "CouponID: " + CouponID + " not found.";
			}

			var result = new
			{
				Status = status
				,
				Message = message
			};
			return new JavaScriptSerializer().Serialize(result);
		}

		//----------------------------------------------------------------------------------------------------
		[WebMethod]
		public string AddUpdateCasino(string CasinoID, string CasinoName)
		{
			string status = "";
			string message = "";

			dbCoupons db = new dbCoupons();
			t_Casino casino;

			if (!string.IsNullOrEmpty(CasinoID))
			{
				casino = db.t_Casinos.SingleOrDefault(c => c.CasinoID == int.Parse(CasinoID));

				if (casino != null)
				{
					casino.Casino = CasinoName;
					try
					{
						db.SubmitChanges();
						status = "success";
						message = string.Format("'{0}' successfully saved.", CasinoName);
					}
					catch (Exception e)
					{
						status = "fail";
						message = e.Message;
					}
				}
				else //casino is null
				{
					status = "fail";
					message = string.Format("CasinoID: '{0}' not found", CasinoID);
				}

			}
			else // CasinoID is not empty
			{
				casino = db.t_Casinos.SingleOrDefault(c => c.Casino.Equals(CasinoName, StringComparison.OrdinalIgnoreCase));

				if (casino != null)
				{
					status = "fail";
					message = string.Format("Casino Name: '{0}' already exists.", CasinoName);
				}
				else
				{
					try
					{
						casino = new t_Casino();
						casino.Casino = CasinoName;

						db.t_Casinos.InsertOnSubmit(casino);
						db.SubmitChanges();

						status = "success";
						message = string.Format("'{0}' successfully saved.", CasinoName);

					}
					catch (Exception e)
					{
						status = "fail";
						message = e.Message;
					}
				}
			}


			var result = new
			{
				Status = status
				,
				Message = message
			};

			return new JavaScriptSerializer().Serialize(result);
		}
        
    }
}
